import { Storage } from '@ionic/storage';
import { ChatserviceProvider, ChatMessage } from './../../providers/chatservice/chatservice';
import { Component,ViewChild } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { LoadingController } from 'ionic-angular/components/loading/loading-controller';
import { RestProvider } from '../../providers/rest/rest';
import { Content } from 'ionic-angular/components/content/content';
import { TextInput } from 'ionic-angular/components/input/input';
import { Events } from 'ionic-angular/util/events';

/**
 * Generated class for the ChatDetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-chat-details',
  templateUrl: 'chat-details.html',
})
export class ChatDetailsPage {

  chatUserName: string
  chatUserId: string
  userId: string
  userName: string
  userImgUrl: string
  editorMessage: string
  errorMessage: any
  isOpenEmojiPicker = false
  messageList: ChatMessage[] = []

  @ViewChild(Content) content: Content
  @ViewChild('chatInput') messageInput: TextInput

  constructor(public navCtrl: NavController, 
    public chatservice: ChatserviceProvider,
    public loadCtrl: LoadingController ,
    public rest: RestProvider,
    public storage: Storage,
    public event: Events,
    public navParams: NavParams) {
    this.chatUserName = navParams.get('username')
    this.chatUserId = navParams.get('userid')
    console.log(this)
    
  }

  ionViewDidEnter(){
    this.storage.get('userId').then((val)=> {
      if(val!=null) {
        // 加载用户数据
        this.rest.getUserInfo(val)
        .subscribe(
          userinfo => {
            this.userId = '5996953615f87ec629cff319'
            this.userName = userinfo["UserNickName"]
            this.userImgUrl = userinfo["UserHeadface"] + "?" + (new Date()).valueOf()
          },
         error=> this.errorMessage = <any>error
        )
      }
    })

   this.getMessages()
   .then(() => {
     this.scrollToBottom()
   })

  //  听取消息的发布，订阅
  this.event.subscribe('chat.received',(msg, time)=>{
    this.messageList.push(msg)
    this.scrollToBottom()
  })
  }

  sendMessage() {
    if (!this.editorMessage.trim()) {
      return
    }
    const id = Date.now().toString()
    let messageSend : ChatMessage = {
      messageId: id,
      userId: this.userId,
      username: this.userName,
      userImgUrl: this.userImgUrl,
      toUserId: this.chatUserId,
      time: Date.now(),
      message: this.editorMessage,
      status: 'pending'
    }

    this.messageList.push(messageSend)
    this.scrollToBottom()
    this.editorMessage = ''

    if(!this.isOpenEmojiPicker){
      this.messageInput.setFocus()
    }
    this.chatservice.sendMessage(messageSend)
    .then(() => {
      let index = this.getMessageIndex(id)
      if (index !== -1) {
        this.messageList[index].status = 'success'
      }
    })
  }

  /**
   * 调用 service 里面的方法进行属性的赋值
   * 
   * @returns 
   * @memberof ChatDetailsPage
   */
  getMessages() {
    return this.chatservice.getMessageList()
    .then(res => {
      this.messageList = res
    })
    .catch(error => {
      console.error(error)
    })  
  }

  /**
   * 切换表情组件
   * 
   * @memberof ChatDetailsPage
   */
  switchEmojiPicker() {
    this.isOpenEmojiPicker = !this.isOpenEmojiPicker
  }

  ionViewWillLeave(){
    this.event.unsubscribe('chat.received')
  }

  focus() {
    this.isOpenEmojiPicker = false
    this.content.resize()
  }

  scrollToBottom(): any {
    setTimeout(() => {
      if (this.content.scrollToBottom) {
        this.content.scrollToBottom()
      }
    }, 400)
  }

  getMessageIndex(id: string): any {
    return this.messageList.findIndex(e => e.messageId === id )
  }
}
